package org.squabble.validator;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.squabble.service.AccountService;
import org.squabble.web.account.PasswordResetCommand;

@Component(value = "passwordResetValidator")
public class PasswordResetValidator implements Validator {

	@Autowired
	AccountService accountService;

	@SuppressWarnings("unchecked")
	@Override
	public boolean supports(Class clazz) {
		return PasswordResetCommand.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object arg0, Errors errors) {
		PasswordResetCommand prc = (PasswordResetCommand) arg0;
		if (StringUtils.isBlank(prc.getEmail())
				&& StringUtils.isBlank(prc.getValidationCode())) {
			errors
					.rejectValue("email",
							"PasswordResetCommand.email[not.blank]");
		}
		if (StringUtils.isNotBlank(prc.getEmail())) {
			if (!accountService.emailExists(prc.getEmail())) {
				errors.rejectValue("email",
						"PasswordResetCommand.email[not.found]");
			}
		}
		if (StringUtils.isNotBlank(prc.getValidationCode())) {
			if (!accountService.validationCodeExists(prc.getValidationCode())) {
				errors.rejectValue("validationCode",
						"PasswordResetCommand.validationCode[not.found]");
			}
		}
	}

}
